package com.kanavi.dataAccess.config;

import com.kanavi.dataAccess.entity.SysDataScope;
import net.sf.jsqlparser.statement.select.PlainSelect;

import java.util.List;
import java.util.Map;

public class ListApiAuthParamsParser extends AbstractApiAuthParamsParser {
  @Override
  public String parse(PlainSelect plainSelect, SysDataScope dataScope, Map<String, Object> params) {
    String sqlPart =
        dataScope.getTableName()
            + "."
            + dataScope.getColumnName()
            + " "
            + dataScope.getExpression();
    for (String s : params.keySet()) {
      String expression = "";
      Object o = params.get(s);
      if (o instanceof List) {
        List<String> list = (List<String>) o;
        expression = this.listParser(list);
      }
      sqlPart = sqlPart.replace(REPLACE_PREFIX + s, expression);
    }
    return sqlPart;
  }

  private String listParser(List<String> list) {
    if (list.size() > 0) {
      StringBuilder str = new StringBuilder(BRACKETS_OPEN);
      for (String s : list) {
        str.append(SEMICOLON).append(s).append(SEMICOLON).append(COMMA);
      }
      String sqlPart = str.substring(0, str.length() - 1);
      sqlPart += BRACKETS_CLOSE;
      return sqlPart;
    }
    return null;
  }
}
